package com.even.camerarecoder

import android.annotation.TargetApi
import android.os.Build
import com.evendai.loglibrary.Timber

import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit


@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
class H264EncoderThread(producer: NgnProxyVideoProducer, isPortrait: Boolean) : Thread(H264EncoderThread::class.java.simpleName) {
    @Suppress("SpellCheckingInspection")
    private var mYUVDatasQueue: BlockingQueue<ByteArray> = LinkedBlockingQueue(5)
    private val mH264Encoder = H264Encoder(producer, isPortrait)
    private var frameLossCount: Int = 0
    private var needRun = true

    @Suppress("SpellCheckingInspection")
    fun addYUVDatas(yuvDatas: ByteArray) {
        if (needRun) {
            val offer = mYUVDatasQueue.offer(yuvDatas)
            if (!offer) {
                Timber.e("丢帧：${++frameLossCount}帧")
            }
        }
    }

    override fun run() {
        try {
            while (needRun) {
                mYUVDatasQueue.poll(30L, TimeUnit.MILLISECONDS)?.let {
                    if (needRun) {
                        mH264Encoder.encodeYuvToH264(it)
                    }
                }
            }
        } catch (e: Exception) {
            Timber.fe(e,"把YUV编码为H264时出现异常")
        }
    }

    fun close() {
        try {
            needRun = false
            mH264Encoder.close()
        } catch (e: Exception) {
            Timber.w(e, "关闭H264编码器时出现异常")
        }
    }

}
